<template>
    <div id="ty-swiper" @mouseleave="leaveSwiper" @mouseenter="enterSwiper">
      <button class="left-btn" @click="leftBtnClick"><</button>
      <button class="right-btn" @click="rightBtnClick">></button>

      <div class="swiper">

      <slot></slot>
      </div>

      <slot name="indicator"></slot>

      <div class="indicator">
        <slot name="indicator" v-if="showIndicator && slideCount > 1">
          <div v-for="(item, index) in slideCount" class="indi-item"
               :class="{active: index === currentIndex-1}" :key="index"
                @click="indicatorClick(index)"></div>
        </slot>
      </div>

    </div>
</template>

<script>
	export default {
		name: "Swiper",
    props: {
      interval: { // 每3秒一次轮播
		    type: Number,
        default: 4000
      },
      animDuration: { // 动画时长
		    type: Number,
        default: 300
      },
      moveRatio: { //
        type: Number,
        default: 0.25
      },
      showIndicator: { // 圆点展示
        type: Boolean,
        default: true
      }
    },
    data: function () {
		  return {
        slideCount: 0, // 元素个数
        totalWidth: 0, // swiper的宽度
        swiperStyle: {}, // swiper样式
        currentIndex: 1, // 当前的index
        scrolling: false, // 是否正在滚动
      }
    },
    mounted: function () {
      // 1.操作DOM, 在前后添加Slide
      setTimeout(() => {
        this.handleDom();

        // 2.开启定时器
        this.startTimer();
      }, 600) // 600ms后开启定时器,如果开启的延迟过短，会导致轮播图轮播失效
    },
    methods: {

		  /**有左右按钮触发的函数*/
      leftBtnClick () {
        this.stopTimer();

        this.changeItem(-1)
      },
      rightBtnClick () {
        this.stopTimer();

        this.changeItem(1) // 其里面还有一个计时器不能直接调用，否则就会出现多个计时器
      },

      /**点击对应的点时*/
      indicatorClick (index) {
        // 1.移除定时器
        this.stopTimer();

        this.currentIndex = index + 1 // 当前的index变成这个index + 1
        this.scrollContent(-this.currentIndex * this.totalWidth); // 根据当前的index进行滚动轮播

        // 2.添加定时器
        this.startTimer(); // 添加定时器,以使轮播能够正常的执行下次

      },

      /**鼠标移入移出轮播图*/
      enterSwiper () {
        // console.log('移入');
        // this.stopTimer();
      },
      leaveSwiper () { // mouseout: 指针移出元素，或者移到它的子元素上。
        // this.stopTimer();
        // console.log('移出');
        // this.startTimer();
        // this.scrollContent(-this.currentIndex * this.totalWidth);
      },


		  /**
       * 定时器操作
       */
      startTimer: function () {
		    this.playTimer = window.setInterval(() => {
		      this.currentIndex++;
		      this.scrollContent(-this.currentIndex * this.totalWidth);
        }, this.interval)
      },
      stopTimer: function () {
        window.clearInterval(this.playTimer);
      },

      /**
       * 滚动到正确的位置
       */
      scrollContent: function (currentPosition) {
        // 0.设置正在滚动
        this.scrolling = true;

        // 1.开始滚动动画
        this.swiperStyle.transition ='transform '+ this.animDuration + 'ms';
        this.setTransform(currentPosition);

        // 2.判断滚动到的位置
        this.checkPosition();

        // 4.滚动完成
        this.scrolling = false
      },

      /**
       * 校验正确的位置
       */
      checkPosition: function () {
        window.setTimeout(() => {
          // 1.校验正确的位置
          this.swiperStyle.transition = '0ms';
          if (this.currentIndex >= this.slideCount + 1) {
            this.currentIndex = 1;
            this.setTransform(-this.currentIndex * this.totalWidth);
          } else if (this.currentIndex <= 0) {
            this.currentIndex = this.slideCount;
            this.setTransform(-this.currentIndex * this.totalWidth);
          }

          // 2.结束移动后的回调
          this.$emit('transitionEnd', this.currentIndex-1);
        }, this.animDuration)
      },

      /**
       * 设置滚动的位置
       */
      setTransform: function (position) {
        this.swiperStyle.transform = `translate3d(${position}px, 0, 0)`;
        this.swiperStyle['-webkit-transform'] = `translate3d(${position}px), 0, 0`;
        this.swiperStyle['-ms-transform'] = `translate3d(${position}px), 0, 0`;
      },

      /**
       * 操作DOM, 在DOM前后添加Slide
       */
		  handleDom: function () {
        // 1.获取要操作的元素
        let swiperEl = document.querySelector('.swiper');
        let slidesEls = swiperEl.getElementsByClassName('slide');

        // 2.保存个数
        this.slideCount = slidesEls.length;

        // 3.如果大于1个, 那么在前后分别添加一个slide
        if (this.slideCount > 1) {
          let cloneFirst = slidesEls[0].cloneNode(true);
          let cloneLast = slidesEls[this.slideCount - 1].cloneNode(true);
          swiperEl.insertBefore(cloneLast, slidesEls[0]);
          swiperEl.appendChild(cloneFirst);
          this.totalWidth = swiperEl.offsetWidth;
          this.swiperStyle = swiperEl.style;
        }

        // 4.让swiper元素, 显示第一个(目前是显示前面添加的最后一个元素)
        this.setTransform(-this.totalWidth);
      },

      /**
       * 控制上一个, 下一个
       */
      previous: function () {
        // this.stopTimer();
        this.changeItem(-1);
      },

      next: function () {
        // this.stopTimer();
        this.changeItem(1);
      },

      changeItem: function (num) {
        // 1.移除定时器
        this.stopTimer();

        // 2.修改index和位置
        this.currentIndex += num;
        this.scrollContent(-this.currentIndex * this.totalWidth);

        // 3.添加定时器
        this.startTimer();
      }
    }
	}
</script>

<style scoped>
  #ty-swiper {
    overflow: hidden;
    position: relative;

  }

  .left-btn {
    position: absolute;
    left: 0;
    height: 100%;
    width: 2%;

    border-radius: 60px;
    font-size: 60px;

    cursor: pointer;/*鼠标放上变手指*/

    outline: none;
    border: none;

    opacity: 0.1;
    z-index: 1;

  }
  .right-btn {
    position: absolute;
    right: 0;
    height: 100%;
    width: 2%;

    border-radius: 60px;
    font-size: 60px;

    cursor: pointer;/*鼠标放上变手指*/

    outline: none;
    border: none;

    opacity: 0.1;
    z-index: 1;
  }

  .swiper {
    display: flex;
  }

  .indicator {
    display: flex;
    justify-content: center;
    position: absolute;
    width: 100%;
    bottom: 8px;
  }

  .indi-item {
    box-sizing: border-box;
    width: 8px;
    height: 8px;
    border-radius: 4px;
    background-color: #fff;
    line-height: 8px;
    text-align: center;
    font-size: 12px;
    margin: 0 5px;

    cursor: pointer;/*鼠标放上变手指*/

  }
  .indi-item:hover {
    background-color: rgba(212,62,46,0.5);
  }
  .indi-item.active {
    background-color: rgba(212,62,46,1);
  }
</style>
